<template>
  <div class="allocationContent" v-loading.fullscreen.lock="taskloading">
    <div class="allocationContentRight">
      <div class="allocationAttentionRight">
        <div
          style="
            height: 54px;
            background: #1a48db33;
            padding: 0 15px;
            text-decoration: underline;
            color: #1a48db;
            line-height: 54px;
            cursor: pointer;
            transform: translateX(-14px);
          "
          @click="gobacktop"
        >
          &lt; {{ schoolcon.schoolName }}
        </div>
        <div class="aarbottom">
          <span style="display: inline-block; padding-right: 20px"
            >新教师分配规则</span
          >
          <el-radio-group v-model="taskmoshi" @change="changetaskmoshi">
            <el-radio-button :label="3">自由模式</el-radio-button>
            <el-radio-button :label="2">平均模式</el-radio-button>
            <el-radio-button :label="1">定量模式</el-radio-button>
          </el-radio-group>
          <!-- <el-select v-model="assignedteacher.preference" placeholder="请选择" @change="preferencechange">
                        <el-option
                            v-for="item in questiontz"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select> -->
        </div>
      </div>
      <div class="tableStyle">
        <div class="aartop">
          <span
            >题组任务量：<i>{{ schoolcon.totalAssignments }}</i></span
          >
          <span
            >已分配教师：<i>{{ schoolcon.assignedTeachers }}</i></span
          >
          <span
            >已分配：<i>{{ schoolcon.completedAssignments }}</i></span
          >
          <span
            >待分配：<i>{{ schoolcon.pendingAssignments }}</i></span
          >
        </div>

        <el-table
          :data="assignedteacher"
          border
          :span-method="objectSpanMethod"
        >
          <el-table-column label="题组" align="center">
            <template slot-scope="scope">
              {{ scope.row.questionGroupName || scope.row.questionNumbers }}
            </template>
          </el-table-column>
          <el-table-column prop="teacherName" label="已分配教师" align="center">
          </el-table-column>
          <el-table-column prop="phone" label="手机号" align="center">
          </el-table-column>
          <el-table-column
            prop="schoolTaskCount"
            label="校任务量"
            align="center"
          >
          </el-table-column>
          <el-table-column label="教师任务量" align="center">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.edit"
                v-model="scope.row.planTasks"
                @input="scope.row.planTasks = onlyNumber(scope.row.planTasks)"
              ></el-input>
              <span v-else>{{ scope.row.planTasks }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="completedTasks" label="已评" align="center">
          </el-table-column>
          <el-table-column prop="remainingTasks" label="剩余" align="center">
          </el-table-column>
          <el-table-column v-if="taskmoshi == 1" label="操作" align="center">
            <template slot-scope="scope">
              <el-link type="primary" @click="tjjs(scope.$index)"
                >添加教师</el-link
              >
              <el-link
                v-if="!scope.row.edit"
                type="primary"
                @click="xgrw(scope.row)"
                >修改任务</el-link
              >
              <el-link v-else type="success" @click="bcrw(scope.row)"
                >保存任务</el-link
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- <div class="buttonsetlist">
        <span @click="teacheroptionquestion">保存</span>
      </div> -->
    </div>

    <el-dialog title="请选择评阅教师" :visible.sync="tjjsModal" width="400px">
      <el-select v-model="tjjsIndex" placeholder="请选择评阅教师">
        <el-option
          v-for="(item, index) in Teacherstobeassigned"
          :key="item.teacherId"
          :label="item.teacherName"
          :value="index"
          :disabled="disTeacher(item.teacherId)"
        ></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tjjsModal = false">取 消</el-button>
        <el-button type="primary" @click="tjjsbc">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getassignedTeachers,
  Gettaskteacherlist,
  taskteacherStats,
  taskteacherStatsUpdate,
  taskschoolUpdateEditAssignmnetType,
  getSchoolConfig,
} from "@/api/task/task.js";
export default {
  props: ["examsubjectid"],
  data() {
    return {
      Teacherstobeassigned: [],
      rowspanData: {},
      assignedteacher: [],
      schoolcon: {},
      taskmoshi: 0,
      isshowloading: true,
      taskloading: false,

      oldTaskmoshi: "",

      tjjsModal: false,
      tjjsIndex: "",
      tableIndex: "",
      editMergeNumber: "",
    };
  },
  mounted() {
    // this.examsubjectid = sessionStorage.getItem('examSubjectId')
    this.notfountlist();
    this.listfpteacher();
    this.schoolcon = JSON.parse(sessionStorage.getItem("taskshooltap"));
    // this.taskmoshi = JSON.parse(
    //   sessionStorage.getItem("taskshooltap")
    // ).assignmentRule;
  },
  watch: {
    examsubjectid(newVal, oldVal) {
      // 确保值确实发生了变化（避免初始化时的误触发）
      if (newVal !== oldVal) {
        this.notfountlist();
        this.listfpteacher();
      }
    },
  },
  methods: {
    //分配模式弹框
    changetaskmoshi(val) {
      this.taskmoshi = val;
      if (val != 1) {
        this.$modal
          .confirm(
            `变更至${
              this.taskmoshi == 1
                ? "自由模式"
                : this.taskmoshi == 2
                ? "平均模式"
                : "定量模式"
            }模式后，将覆盖原有设置题量！`
          )
          .then(() => {
            this.addtasksure();
          })
          .catch(() => {
            this.taskmoshi = this.oldTaskmoshi;
          });
      } else {
        this.addtasksure();
      }
    },
    //确认修改分配模式
    addtasksure() {
      this.oldTaskmoshi = this.taskmoshi;
      let data = {
        id: this.schoolcon.id,
        assignmnetType: this.taskmoshi,
      };
      this.taskloading = true;
      taskschoolUpdateEditAssignmnetType(data)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.listfpteacher();
          }
        })
        .catch(() => {
          this.taskloading = false;
        });
    },
    //返回上一级
    gobacktop() {
      this.$emit("gobacktop", "Schoolallocationsituation");
    },
    //未分配的教师
    notfountlist() {
      let query = {
        examId: this.examsubjectid,
        schoolId: JSON.parse(sessionStorage.getItem("taskshooltap")).schoolId,
        // assignmentConfigId:JSON.parse(sessionStorage.getItem('taskshooltap')).id
      };
      getassignedTeachers(query).then((res) => {
        if (res.code == 200) {
          this.Teacherstobeassigned = res.data;
        }
      });
    },

    initTable(rows) {
      let rowspanData = {};

      this.assignedteacher = rows.map((item) => {
        item.mergeNumber = item.questionGroupName
          ? item.questionGroupName
          : item.questionNumbers;
        let data = {
          ...item,
        };
        if (!rowspanData[item.mergeNumber]) {
          rowspanData[item.mergeNumber] = [item];
          data.rowspan = true;
        } else {
          rowspanData[item.mergeNumber].push(item);
        }

        return data;
      });

      this.rowspanData = rowspanData;
    },
    // 已分配教师
    listfpteacher() {
      getSchoolConfig({
        examId: this.examsubjectid,
        schoolId: JSON.parse(sessionStorage.getItem("taskshooltap")).schoolId,
      }).then((res) => {
        this.taskmoshi = res.data.assignmentRule;
        this.oldTaskmoshi = this.taskmoshi;
      });

      this.taskloading = true;
      let query = {
        examId: this.examsubjectid,
        schoolId: JSON.parse(sessionStorage.getItem("taskshooltap")).schoolId,
      };
      Gettaskteacherlist(query)
        .then((res) => {
          if (res.code == 200) {
            this.initTable(res.rows);
          }
        })
        .finally(() => {
          this.taskloading = false;
        });
    },

    onlyNumber(value) {
      return value.replace(/[^0-9]/g, "");
    },
    //保存
    // teacheroptionquestion() {
    //   this.taskloading = true;
    //   taskteacherStatsUpdate(this.assignedteacher)
    //     .then((res) => {
    //       if (res.code == 200) {
    //         this.listfpteacher();
    //         this.$message({
    //           message: "分配成功",
    //           type: "success",
    //         });
    //       }
    //     })
    //     .finally(() => {
    //       this.taskloading = false;
    //     });
    // },
    bcrw(row) {
      let arr = this.assignedteacher.filter((item) => {
        return item.mergeNumber == row.mergeNumber;
      });

      let verify = arr.every((item) => {
        return item.planTasks >= item.completedTasks;
      });

      if (!verify) {
        this.$modal.alertError("输入的任务数量不能小于已评的数量");
        return;
      }

      const sum = arr.reduce((acc, curr) => acc + Number(curr.planTasks), 0);
      if (sum != row.schoolTaskCount) {
        this.$modal.alertError("输入的任务数量与校任务量不匹配");
        return;
      }

      this.taskloading = true;
      taskteacherStatsUpdate(arr)
        .then((res) => {
          if (res.code == 200) {
            this.listfpteacher();
            this.$message({
              message: "分配成功",
              type: "success",
            });
          }
        })
        .finally(() => {
          this.taskloading = false;
        });
    },

    objectSpanMethod({ row, column }) {
      if (
        column.label == "题组" ||
        column.label == "校任务量" ||
        column.label == "操作"
      ) {
        if (row.rowspan == true) {
          return {
            rowspan: this.rowspanData[row.mergeNumber].length,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      }
    },
    tjjs(tableIndex) {
      this.tableIndex = tableIndex;
      this.tjjsIndex = "";
      this.tjjsModal = true;
    },
    xgrw(row) {
      let mergeNumber = row.mergeNumber;
      this.assignedteacher = this.assignedteacher.map((item) => {
        return {
          ...item,
          edit: item.mergeNumber == mergeNumber,
        };
      });
    },
    tjjsbc() {
      let assignedteacher = JSON.parse(JSON.stringify(this.assignedteacher));
      let data = assignedteacher[this.tableIndex];
      assignedteacher.splice(
        this.tableIndex + this.rowspanData[data.mergeNumber].length,
        0,
        {
          ...this.Teacherstobeassigned[this.tjjsIndex],
          questionGroupName: data.questionGroupName,
          questionNumbers: data.questionNumbers,
          schoolTaskCount: data.schoolTaskCount,
          assignmentConfigId: data.assignmentConfigId,
          planTasks: "",
        }
      );
      this.initTable(assignedteacher);
      this.tjjsModal = false;
      this.xgrw(data);
    },

    disTeacher(teacherId) {
      if (this.tableIndex !== "") {
        let mergeNumber = this.assignedteacher[this.tableIndex].mergeNumber;
        return this.rowspanData[mergeNumber].some((item) => {
          return item.teacherId == teacherId;
        });
      } else {
        return true;
      }
    },
  },
};
</script>
<style>
.allocationContentRight
  .el-table--enable-row-hover
  .el-table__body
  tr:hover
  > td.el-table__cell {
  background-color: transparent !important;
}
</style>
<style scoped>
.allocationContent {
  display: flex;
  /* align-items: center; */
  justify-content: space-between;
  margin-top: 14px;
}
.allocationAttentionLeft {
  box-sizing: border-box;
  width: 290px;
  height: 54px;
  background: #e8f0fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}
.allocationAttentionLeft span {
  color: #557292;
}
.allocationAttentionLeft span i {
  font-style: normal;
  color: #295cff;
}
.allocationAttentionLeft b {
  cursor: pointer;
  font-weight: normal;
  color: #295cff;
}
.allocationContentLeft,
.allocationContentRight {
  border: solid 1px #e8f0fa;
  background: #fff;
}
.allocationContentRight {
  width: 100%;
}
.tableStyle {
  background: #fff;
  padding: 14px;
  overflow-y: auto;
  overflow-x: hidden;
}
.tableStyle::-webkit-scrollbar {
  width: 4px;
  background-color: #eee;
}
.tableStyle::-webkit-scrollbar-track {
  background-color: #eee;
}
.tableStyle::-webkit-scrollbar-thumb {
  background: #619cf5;
}
.tableStyle table {
  border: 1px solid rgba(216, 228, 240, 0.5);
}
.tableStyle table tr th {
  font-size: 14px;
  font-weight: normal;
  background: #e8f0fa;
  height: 42px;
}
.tableStyle table tr th:first-child {
}
.tableStyle table tr th:last-child {
}
.tableStyle table tr td {
  height: 42px;
  text-align: center;
  font-size: 14px;
  border-right: solid 1px rgba(216, 228, 240, 0.34);
}
.tableStyle table tr td:last-child {
  border-right: none;
}
.tableStyle table tr td i {
  font-style: normal;
  font-size: 12px;
  color: #999;
}
.tableStyle table tr td button {
  display: flex;
  align-items: center;
  color: #295cff;
  justify-content: center;
  cursor: pointer;
  border: none;
  background: none;
}
.tableStyle table tr td button em {
  font-size: 12px;
  font-style: normal;
  margin-left: 5px;
}
.tableStyle table tr td div.caozuo button {
  width: auto;
}
.tableStyle table tr td button.yichuteacher {
  color: #ec555a;
}
.tableStyle table tr td button.yichuteacher1 {
  color: #999;
}
.tableStyle table tr:nth-child(3n) {
  background: #fafafb;
}
.tableStyle table tr td >>> .el-input__inner {
  width: 150px;
  height: 30px;
  border: 1px solid #d8e4f0;
}
.tableStyle table tr td >>> .el-input__icon {
  line-height: 30px;
}
.buttonBox {
  width: 100%;
  height: 60px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.buttonBox b {
  width: 124px;
  height: 34px;
  background: #1a48db;
  font-weight: normal;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  text-align: center;
  line-height: 34px;
  margin: 0 8px;
  border-radius: 10px;
}
.buttonBox b:nth-child(2) {
  background: #1a48db;
  border: 1px solid #295cff;
  color: #295cff;
}
.allocationAttentionRight {
  box-sizing: border-box;
  width: 100%;
  height: 54px;
  background: #e8f0fa;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  padding: 0 14px;
}
.aartop {
  color: #557292;
  font-size: 14px;
  padding-bottom: 15px;
}
.aartop span {
  margin-right: 14px;
}
.aartop i {
  font-style: normal;
  color: #295cff;
}
.aarbottom {
  color: #557292;
  display: flex;
  align-items: center;
  height: 30px;
}
.aarbottom >>> .el-radio {
  margin-right: 15px;
}
.aarbottom >>> .el-radio__label {
  padding-left: 5px;
}
.aarbottom >>> .el-input__inner {
  width: 188px;
  height: 34px;
  background: #ffffff;
  border: 1px solid #d8e4f0;
  line-height: 34px;
}
.aarbottom >>> .el-input__icon {
  line-height: 34px;
}
.aarbottom em {
  width: 124px;
  height: 34px;
  background: #295cff;
  font-style: normal;
  font-size: 14px;
  color: #fff;
  text-align: center;
  line-height: 34px;
  margin-left: 14px;
}
.addExamMain {
  position: fixed;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  left: 0;
  top: 0;
  z-index: 10000;
}
.addExamContent {
  width: 600px;
  height: auto;
  background: #ffffff;
  box-shadow: 0px 4px 16px 0px rgba(85, 114, 146, 0.1);
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
  box-sizing: border-box;
  padding: 30px;
}
.addtask p,
.disassembletask p {
  font-size: 14px;
  color: #295cff;
  padding: 14px 0;
}
.pytaskContent {
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pytaskContent span {
}
.pytaskContent span i {
  font-style: normal;
  color: #ec555a;
}
.dfpbox {
  display: flex;
  padding-top: 15px;
  font-size: 14px;
  align-items: center;
  width: 100%;
}
.dfpbox >>> .el-input {
  width: 100px;
}
.dfpbox >>> .el-input__inner {
  width: 80px;
  margin-left: 10px;
  height: 34px;
  border: 1px solid #d8e4f0;
}
.groupbutton {
  display: flex;
  align-items: center;
  padding-top: 20px;
  justify-content: center;
}
.groupbutton >>> .el-button {
  width: 124px;
  height: 34px;
  background: #295cff;
  font-size: 14px;
  color: #ffffff;
  padding: 0;
}
.groupbutton >>> .el-button:last-child {
  background: #f2f6fb;
  border: 1px solid #295cff;
  color: #295cff;
  margin-left: 24px;
}
.buttonsetlist {
  display: flex;
  justify-content: center;
  padding: 15px;
}
.buttonsetlist span {
  width: 124px;
  height: 34px;
  background: #1a48db;
  font-weight: normal;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  text-align: center;
  line-height: 34px;
  margin: 0 8px;
  border-radius: 10px;
}
.buttonsetlist span:last-child {
  background: #f2f6fb;
  border: 1px solid #295cff;
  border-radius: 10px;
  color: #1a48db;
}
</style>